﻿namespace WebPacker.Configuration
{
	using System;
	using System.Collections.Generic;
	using System.Xml;
	using WebPacker.Packs;

	internal class PackFileInfo
	{
		private readonly string fileName;
		private readonly string packName;
		private readonly PackType packType;

		public PackFileInfo(PackType packType, string packName, string fileName)
		{
			this.packType = packType;
			this.packName = packName;
			this.fileName = fileName;
		}

		public string PackName
		{
			get { return packName; }
		}

		public string FileName
		{
			get { return fileName; }
		}

		public PackType PackType
		{
			get { return packType; }
		}

		public static IEnumerable<PackFileInfo> Deserialize(string filePath)
		{
			using (var reader = XmlTextReader.Create(filePath))
			{
				return Deserialize(reader);
			}
		}

		public static IEnumerable<PackFileInfo> Deserialize(XmlReader reader)
		{
			var packs = new List<PackFileInfo>();

			while (reader.Read())
			{
				if (reader.NodeType == XmlNodeType.Element)
				{
					if (reader.Name != "packs")
					{
						throw new ArgumentException("Expected element \"packs\".");
					}
				}

				break;
			}

			while (reader.Read())
			{
				if (reader.NodeType == XmlNodeType.Element && reader.Name == "pack")
				{
					var name = reader.GetAttribute("name");
					var typeName = reader.GetAttribute("type");
					var fileName = reader.ReadString().Trim();
					var type = (PackType)Enum.Parse(typeof(PackType), typeName, true);
					packs.Add(new PackFileInfo(type, name, fileName));
				}
			}

			return packs;
		}

		public static void Serialize(string filePath, IEnumerable<PackFileInfo> items)
		{
			var settings = new XmlWriterSettings
			{
				Indent = true
			};

			using (var writer = XmlWriter.Create(filePath, settings))
			{
				Serialize(writer, items);
			}
		}

		public static void Serialize(XmlWriter writer, IEnumerable<PackFileInfo> items)
		{
			writer.WriteStartElement("packs");

			foreach (var item in items)
			{
				var typeName = item.PackType.ToString();
				typeName = char.ToLowerInvariant(typeName[0]) + typeName.Substring(1);
				writer.WriteStartElement("pack");
				writer.WriteAttributeString("name", item.PackName);
				writer.WriteAttributeString("type", typeName);
				writer.WriteValue(item.FileName);
				writer.WriteEndElement();
			}

			writer.WriteEndElement();
		}
	}
}